package gis.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;
import com.supermap.android.commons.EventStatus;
import com.supermap.android.maps.CoordinateReferenceSystem;
import com.supermap.android.maps.DefaultItemizedOverlay;
import com.supermap.android.maps.LayerView;
import com.supermap.android.maps.LineOverlay;
import com.supermap.android.maps.MapView;
import com.supermap.android.maps.Overlay;
import com.supermap.android.maps.Point2D;
import com.supermap.android.maps.PolygonOverlay;
import com.supermap.android.maps.measure.MeasureResult;
import com.supermap.android.maps.query.FilterParameter;
import com.supermap.android.maps.query.QueryByGeometryParameters;
import com.supermap.android.maps.query.QueryByGeometryService;
import com.supermap.android.maps.query.QueryEventListener;
import com.supermap.android.maps.query.QueryResult;
import com.supermap.android.maps.query.SpatialQueryMode;
import com.supermap.services.components.commontypes.Feature;
import com.supermap.services.components.commontypes.Geometry;
import com.supermap.services.components.commontypes.GeometryType;

import java.util.ArrayList;
import java.util.List;

public class MapShow2 extends Activity {

    public static String DEFAULT_URL;
//public static final String DEFAULT_URL = "http://125.220.159.168:8090/iserver/services/map-lake/rest/maps/lakeMap";

    static {
        DEFAULT_URL = "http://"+MyApplication.share().getResources().getString(R.string.superMap_ip)+":8090/iserver/services/map-lake/rest/maps/lakeMap";
    }
    protected MapView mapView;
    protected LocationManager locationManager;
    protected Location location;
    public static double d_longitude, d_latitude;
    public final double offsetX = 0, offsetY = 0;//武汉经纬度与lake偏离量
    Bitmap bitmap_mark;
    public Point2D locationPoint2D;
    //定位信息展示控件
    private View m_DetailLayout;
    private PopupWindow pwDetailInfo;
    private TextView m_textLongitude, m_textLatitude, tv_positionValue;
    // 触屏的x坐标
    private int touchX;
    // 触屏的y坐标
    private int touchY;
    private Point2D longTouchGeoPoint = null;
    private DefaultItemizedOverlay blueMarkerOverlay = null;// 长按标注测面积
    // 输入坐标查询
    private View m_DetailLayout_query;
    private PopupWindow pwDetailInfo_query;
    private TextView m_textfarmCode, m_textfarmDLMC, m_textfarmQSDWMC, m_textfarmZLDWMC;
    private TextView m_textfarmTBMJ, m_textfarmTBDLMJ, m_textfarmXZDWMJ, m_textfarmLXDWMJ;
    //量算菜单控件
    // 显示量算结果的编辑文本控件
    private EditText text;
    // 线面触屏Overlay，用来获取点坐标
    private TouchOverlay touchOverlay;
    // 存放绘制线或面的点集合
    private List<Point2D> geoPoints = new ArrayList<Point2D>();
    // 绘制要素状态
    private int drawStatic = -1;// 0代表绘制线，1表示绘制面
    // 默认的绘制面对象
    private PolygonOverlay polygonOverlay;
    // 默认的绘制线对象
    private LineOverlay lineOverlay;
    // 是否发生多点触碰
    public boolean isMultiTouch = false;
    private LocationListener listener,listener2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_show2);
        //初始界面显示地图
        initMapShow();
        // 创建LocationManager对象
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 判断是否打开GPS或者网络
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        final boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gps) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("提高\"我的位置\"精确度").
                    setMessage("如需获取更精确的位置服务，请您在室外时执行以下操作:\n在位置设置中打开GPS").
                    setIcon(R.drawable.location_mark2).
                    setNeutralButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }).
                    create();
            alertDialog.show();
            String str = "GPS没有开!";
            Log.i("GPSmeiyuukai:", str);
        }
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!network) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("提高\"我的位置\"精确度").
                    setMessage("如需获取更精确的位置服务，请您在室内时执行以下操作:\n 打开WLAN").
                    setIcon(R.drawable.location_mark2).
                    setNeutralButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
                            Intent myIntent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                            startActivity(myIntent);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }).
                    create();
            alertDialog.show();
            String str = "Network没有开!";
            Log.i("WLANmeiyuukai:", str);
        }
        // 从NetWork获取最近的最近的定位信息
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        updateLocation(location);
        System.out.println("hellooooo2:" + d_longitude + "," + d_latitude);
        // 设置每1秒获取一次GPS的定位信息
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 1, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 当GPS定位信息发生改变时，更新位置
                updateLocation(location);
                System.out.println("hellooooo3:" + d_longitude + "," + d_latitude);
            }

            @Override
            public void onProviderDisabled(String provider) {
                updateLocation(null);
            }

            @Override
            public void onProviderEnabled(String provider) {
                // 当GPS LocationProvider可用时，更新位置
                updateLocation(locationManager.getLastKnownLocation(provider));
            }

            @Override
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
            }
        });
        // 显示定位信息
        //longitude = (TextView) findViewById(R.id.longitude);
        //latitude = (TextView) findViewById(R.id.latitude);
        // 定位
        Button btn_location = (Button) findViewById(R.id.button_location);
        btn_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (location != null) {
                    Point2D point2D2 = new Point2D(location.getLongitude() + offsetX, location.getLatitude() + offsetY);
                    setPoint2DOnMap(point2D2);

                } else {
                    Toast.makeText(MapShow2.this, "不能获取位置服务，请检查", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //删除overlay
        Button btn_deleteoverlay = (Button) findViewById(R.id.button_deleteoverlay);
        btn_deleteoverlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //mapView.removeOverlayByKey();
                mapView.removeOverlayByKey("locationOverlay");
                //mapView.getOverlays().remove(myOwnOverlay);
                //initMapShow();

                if(null!=pwDetailInfo){
                    pwDetailInfo.dismiss();
                }
                if(null!=pwDetailInfo_query){
                    pwDetailInfo_query.dismiss();
                }


                clear();
            }
        });

        // 打开上传模块
        Button btn_upload = (Button) findViewById(R.id.button_collectLocation);
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapShow2.this, UploadPoint.class);
                MapShow2.this.startActivity(intent);
            }
        });

        // 回到初始界面
        Button btn_backEntire = (Button) findViewById(R.id.button_back);
        btn_backEntire.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mapView.removeOverlayByKey("locationOverlay");
                //mapView.getOverlays().remove(myOwnOverlay);
                //initMapShow();
                clear();
                backTOInitMapShow();
            }
        });

        // 初始化信息展示控件
        LayoutInflater lfCallOut = getLayoutInflater();
        m_DetailLayout = lfCallOut.inflate(R.layout.detailinfo, null);
        pwDetailInfo = new PopupWindow(m_DetailLayout,LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        m_textLongitude = (TextView) m_DetailLayout.findViewById(R.id.textview_longitude);
        m_textLatitude = (TextView) m_DetailLayout.findViewById(R.id.textview_latitude);
        tv_positionValue = (TextView) m_DetailLayout.findViewById(R.id.textview_farmQSDWMC);
        mapView.getOverlays().add(new TouchOverlayPoint());
        // 初始化用水地信息展示控件
        LayoutInflater lfCallOut_query = getLayoutInflater();
        m_DetailLayout_query = lfCallOut_query.inflate(R.layout.farmlandinfo, null);
        pwDetailInfo_query = new PopupWindow(m_DetailLayout_query, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        m_textfarmDLMC = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmDLMC);
        m_textfarmCode = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmCode);
        m_textfarmQSDWMC = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmQSDWMC);
        m_textfarmZLDWMC = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmZLDWMC);
        m_textfarmTBMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmTBMJ);
        m_textfarmTBDLMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmTBDLMJ);
        m_textfarmXZDWMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmXZDWMJ);
        m_textfarmLXDWMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmLXDWMJ);

        //量算按钮弹出菜单量算距离和面积
        LayoutInflater lfCallOut_mearsure = getLayoutInflater();
        View m_DetailLayout_mearsure=lfCallOut_mearsure.inflate(R.layout.measure_menu, null);
        final PopupWindow pwDetailInfo_mearsure = new PopupWindow(m_DetailLayout_mearsure, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView m_textdistance=(TextView) m_DetailLayout_mearsure.findViewById(R.id.txt_distance);
        TextView m_textarea=(TextView)m_DetailLayout_mearsure.findViewById(R.id.txt_area);
        TextView m_textclear=(TextView)m_DetailLayout_mearsure.findViewById(R.id.txt_clear);
        text = (EditText) this.findViewById(R.id.editText);
        touchOverlay = new TouchOverlay();
        lineOverlay = new LineOverlay(getLinePaint());
        mapView.getOverlays().add(lineOverlay);
        polygonOverlay = new PolygonOverlay(getPolygonPaint());
        mapView.getOverlays().add(polygonOverlay);
        Button btn_measure=(Button) findViewById(R.id.button_mearsure);
        final boolean[] show = {true};
        btn_measure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //openOptionsMenu();
                if(show[0]){
                    pwDetailInfo_mearsure.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置
                    show[0] =false;
                }else{
                    pwDetailInfo_mearsure.dismiss();//popwindow消失
                    show[0] =true;
                }
            }
        });
        m_textdistance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("helloooooooo量算距离");
                pwDetailInfo_mearsure.dismiss();//popwindow消失
                show[0] =true;
                showDiatanceMeasure();
            }
        });
        m_textarea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwDetailInfo_mearsure.dismiss();//popwindow消失
                show[0] =true;
                showAreaMeasure();
            }
        });
        m_textclear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwDetailInfo_mearsure.dismiss();//popwindow消失
                show[0] =true;
                clear();
            }
        });
        //输入经纬度查询地块信息
        Button btn_querylocation=(Button) findViewById(R.id.button_querylocation);
        btn_querylocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final TableLayout queryDialog = (TableLayout) getLayoutInflater().inflate(R.layout.location_query, null);
                Dialog alertDialog = new AlertDialog.Builder(MapShow2.this)
                        .setTitle("请输入经纬度")
                        .setIcon(R.drawable.location_mark2)
                        .setView(queryDialog)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Point2D point2D1 = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 18.0 / 60 + 20.97 / 3600);
                                EditText m_longitude = (EditText) queryDialog.findViewById(R.id.edittext_longitude);
                                EditText m_latitude = (EditText) queryDialog.findViewById(R.id.edittext_latitude);
                                String longitude = m_longitude.getText().toString();
                                String latitude = m_latitude.getText().toString();
                                //Double d_longitude = Double.parseDouble(longitude);
                                //Double d_latitude = Double.parseDouble(latitude);
                                if (longitude.length()==0&&latitude.length()==0&&longitude == null || latitude == null||longitude.equals("") || latitude.equals("") ) {
                                    Toast.makeText(MapShow2.this, "请完整输入经纬度", Toast.LENGTH_SHORT).show();
                                }else if(0 < Double.parseDouble(longitude) && Double.parseDouble(longitude) < 180 && 0 < Double.parseDouble(latitude) && Double.parseDouble(latitude) < 90){
                                    Point2D point2D1 = new Point2D(Double.parseDouble(longitude), Double.parseDouble(latitude));
                                    setQueryLocationOnMap(point2D1);
                                }else {
                                    Toast.makeText(MapShow2.this, "输入经纬度的值不合法，请重新输入", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .create();
                alertDialog.show();
            }
        });
        //以下三行为测试代码，记得删除
        Point2D point2D111 = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 21.0 / 60 + 20.97 / 3600);
        com.supermap.services.components.commontypes.Point2D point2D22222 = new com.supermap.services.components.commontypes.Point2D(point2D111.getX(),point2D111.getY());
        System.out.println("helloo55555:"+point2D22222.x+"|"+point2D22222.y);


        // 2016.5.4更新 添加GPS每隔3秒定位一次
        //Toast.makeText(MapShow.this, "请室外使用", Toast.LENGTH_SHORT).show();
        Button btn_locationGPS = (Button) findViewById(R.id.button_locationgps);
        btn_locationGPS.setTypeface(MyApplication.iconfont);
        btn_locationGPS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(listener2!=null){
                    return;
                }
                if (gps) {
                    //第二个是更新的时间单位毫秒，第三个是更新的距离单位是米
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, (float) 0.1, listener2 = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            // 当GPS定位信息发生改变时，更新位置
                            updateLocation(location);
                            mapView.removeOverlayByKey("locationOverlay");
                            clear();
                            Point2D point2D2 = new Point2D(location.getLongitude() + offsetX, location.getLatitude() + offsetY);
                            setPoint2DOnMap(point2D2);
                            System.out.println("hellooooo3:" + d_longitude + "," + d_latitude);
                        }

                        @Override
                        public void onProviderDisabled(String provider) {
                            updateLocation(null);
                        }

                        @Override
                        public void onProviderEnabled(String provider) {
                            // 当GPS LocationProvider可用时，更新位置
                            updateLocation(locationManager.getLastKnownLocation(provider));
                        }

                        @Override
                        public void onStatusChanged(String provider, int status,
                                                    Bundle extras) {
                        }
                    });
                    mapView.removeOverlayByKey("locationOverlay");
                    clear();
                    Point2D point2D2 = new Point2D(location.getLongitude() + offsetX, location.getLatitude() + offsetY);
                    setPoint2DOnMap(point2D2);
                }
                else {
                    Toast.makeText(MyApplication.share(),"请打开GPS，并至室外",Toast.LENGTH_SHORT).show();
                }

            }
        });

    }//onCreate结束

    // 回到地图初始界面
    public void backTOInitMapShow() {
        Point2D point2D=new Point2D(354653.07,5041490.55);
        mapView.getController().setCenter(point2D);
    }


    //初始界面显示地图
    public void initMapShow() {
        mapView = (MapView) this.findViewById(R.id.mapview);
        LayerView layerView = new LayerView(this);
        layerView.setURL(DEFAULT_URL);
        CoordinateReferenceSystem crs = new CoordinateReferenceSystem();
        crs.wkid = 4326;//当前坐标参考系对应的的 Well Konwn ID 值（简称 WKID）,4326代表地理坐标系中的GCS_WGS_1984
        //layerView.setCRS(crs);
        //设置比例尺数组
        mapView.fixedLevelsEnabled = true;
//        double scales[] = {1.0 / 681710.44500652316,1.0/634896.05678734626, 1.0 / 166434.19191046193, 1/43629.724804176389,1 / 11437.270579065907};
        double scales[] = {8.7433447786951956E-05,5.5957406583649147E-05,3.58127402135354E-05,2.2920153736662548E-05,9.3880949705369826E-06,6.0083807811436869E-06,3.8453636999319584E-06,2.4610327679564567E-06,1.5750609714921329E-06,1.4668984571454359E-06};
        layerView.setScales(scales);
        mapView.setClickable(true);
        mapView.setBuiltInZoomControls(true);
        mapView.addLayer(layerView);
        mapView.invalidate();//刷新地图
        mapView.addMapViewEventListener(new MapViewEventAdapter());
    }

    // 更新坐标
    public void updateLocation(Location newLocation) {
        if (newLocation != null) {
            d_longitude = newLocation.getLongitude();
            d_latitude = newLocation.getLatitude();
            System.out.println("hellooooo1:" + d_longitude + "," + d_latitude);
        } else {
            d_latitude = 0.0;
            d_longitude = 0.0;
        }

    }

    // 地图上标记定位点
    protected void setPoint2DOnMap(Point2D point2D) {
        // 定位到指定点

        //Drawable bitmap_mark = getResources().getDrawable(R.mipmap.min_blue_pin);
        //Point2D point2D1 = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 21.0 / 60 + 20.97 / 3600);
        setLocationPoint2D(point2D);
        Double[] point = Coord.Coord2(point2D.getX(), point2D.getY());
        Point2D point2D1 = new Point2D(point[0],point[1]);
        mapView.getController().setCenter(point2D1);

        MyOwnOverlay myOwnOverlay = new MyOwnOverlay();
        myOwnOverlay.setKey("locationOverlay");//设置瓦片的key，便于删除
        Log.i("helloooooohhh", myOwnOverlay.getKey());
        mapView.getOverlays().add(myOwnOverlay);
        mapView.invalidate();//添加瓦片之后，及时刷新图层
    }

    class MyOwnOverlay extends Overlay {
        Point2D point2D = getLocationPoint2D();
        Double[] point = Coord.Coord2(point2D.getX(), point2D.getY());
        Point2D point2D1 = new Point2D(point[0],point[1]);
        //Point2D point2D1 = new Point2D(132.952386, 45.236658);
        //Point2D point2D1 = new Point2D(point2D.getX()+offsetX, point2D.getY()+offsetY);//18.599785 14.695709
        Paint paint = new Paint();

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // 在目标点的位置绘制
            Point point = mapView.getProjection().toPixels(point2D1, null);
            bitmap_mark = BitmapFactory.decodeResource(getResources(), R.drawable.location_pos);
            canvas.drawBitmap(bitmap_mark, point.x - bitmap_mark.getWidth() / 2, point.y - bitmap_mark.getHeight() / 2, paint);
            //canvas.drawText("★这里是定位点", point.x, point.y, paint);
            System.out.println("hellooo666:"+point.x+"|"+point.y);
        }

        @Override
        public boolean onTap(Point2D point2D, MapView mapView) {
            System.out.println("helloooo" + 123456);
            Point2D point2D_show = new Point2D(getLocation());
            m_textLongitude.setText(Double.toString(point2D_show.getX() + offsetX));
            m_textLatitude.setText(Double.toString(point2D_show.getY() + offsetY));
            Log.i("helloooodingwei:", Double.toString(point2D_show.getX() + offsetX));
//            tv_positionValue.setText(locationName);
            tv_positionValue.setText("待完成");
            //pwDetailInfo.showAtLocation(m_mapControl, Gravity.NO_GRAVITY, 8, 86);
            pwDetailInfo.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置


            m_DetailLayout.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    pwDetailInfo.dismiss();
                }
            });
            return true;
        }

    }
    // 地图上标记输入经纬度查询的定位点
    protected void setQueryLocationOnMap(Point2D point2D) {
        // 定位到指定点

        //Drawable bitmap_mark = getResources().getDrawable(R.mipmap.min_blue_pin);
        //Point2D point2D = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 21.0 / 60 + 20.97 / 3600);
        setLocationPoint2D(point2D);
        QueryLocationOverlay queryLocationOverlay = new QueryLocationOverlay();
        queryLocationOverlay.setKey("locationOverlay");//设置瓦片的key，便于删除
        Log.i("helloooooohhh", queryLocationOverlay.getKey());
        mapView.getOverlays().add(queryLocationOverlay);
        mapView.invalidate();//添加瓦片之后，及时刷新图层
        com.supermap.services.components.commontypes.Point2D point2D1 = new com.supermap.services.components.commontypes.Point2D(point2D.getX(),point2D.getY());
        geometryQuery(point2D1); //查询用水地信息
    }
    class QueryLocationOverlay extends Overlay {
        Point2D point2D = getLocationPoint2D();
        Double[] point = Coord.Coord2(point2D.getX(), point2D.getY());
        Point2D point2D1 = new Point2D(point[0],point[1]);
        //Point2D point2D1 = new Point2D(132.952386, 45.236658);
        //Point2D point2D1 = new Point2D(point2D.getX()+offsetX, point2D.getY()+offsetY);//18.599785 14.695709
                Paint paint = new Paint();

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // 在目标点的位置绘制
            Point point = mapView.getProjection().toPixels(point2D1, null);
            bitmap_mark = BitmapFactory.decodeResource(getResources(), R.drawable.min_blue_pin);
            canvas.drawBitmap(bitmap_mark, point.x - bitmap_mark.getWidth() / 2, point.y - bitmap_mark.getHeight() / 2, paint);
            //canvas.drawText("★这里是定位点", point.x, point.y, paint);
            pwDetailInfo_query.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置
        }

        @Override
        public boolean onTap(Point2D point2D, MapView mapView) {
            System.out.println("helloooo" + 123456);
            Point2D point2D_show = new Point2D(getLocation());
            //pwDetailInfo_query.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置
            m_DetailLayout_query.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    pwDetailInfo_query.dismiss();
                }
            });
            return true;
        }

    }
    // 地图上标记长按定位点
    protected void setLongTouchPoint2DOnMap(Point2D point2D) {
        // 定位到指定点

        //Drawable bitmap_mark = getResources().getDrawable(R.mipmap.min_blue_pin);
        //Point2D point2D = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 21.0 / 60 + 20.97 / 3600);
        setLocationPoint2D(point2D);
        LongTouchOverlay longTouchOverlay = new LongTouchOverlay();
        longTouchOverlay.setKey("locationOverlay");//设置瓦片的key，便于删除
        Log.i("helloooooohhh", longTouchOverlay.getKey());
        mapView.getOverlays().add(longTouchOverlay);
        mapView.invalidate();//添加瓦片之后，及时刷新图层
        Double[] point = Coord.Coord2(point2D.getX(),point2D.getY());
        //com.supermap.services.components.commontypes.Point2D point2D1 = new com.supermap.services.components.commontypes.Point2D(point[0],point[1]);
        com.supermap.services.components.commontypes.Point2D point2D1 = new com.supermap.services.components.commontypes.Point2D(point2D.getX(),point2D.getY());
        geometryQuery(point2D1);
    }
    class LongTouchOverlay extends Overlay {
        Point2D point2D = getLocationPoint2D();
        //Point2D point2D1 = new Point2D(132.952386, 45.236658);
        //Point2D point2D1 = new Point2D(point2D.getX()+offsetX, point2D.getY()+offsetY);//18.599785 14.695709
        Paint paint = new Paint();

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // 在目标点的位置绘制
            Point point = mapView.getProjection().toPixels(point2D, null);
            bitmap_mark = BitmapFactory.decodeResource(getResources(), R.drawable.green_pin_mini);
            canvas.drawBitmap(bitmap_mark, point.x - bitmap_mark.getWidth() / 2, point.y - bitmap_mark.getHeight() / 2, paint);
            //canvas.drawText("★这里是定位点", point.x, point.y, paint);
        }

        @Override
        public boolean onTap(Point2D point2D, MapView mapView) {
            System.out.println("helloooo" + 123456);
            Point2D point2D_show = new Point2D(getLocation());

            pwDetailInfo_query.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置
            m_DetailLayout_query.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    pwDetailInfo_query.dismiss();
                }
            });
            return true;
        }


    }
    /**
     * 触屏Overlay
     */
    class TouchOverlayPoint extends Overlay {
        @Override
        public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
            touchX =  Math.round(event.getX());
            touchY = Math.round(event.getY());
            // 记录点击位置
            longTouchGeoPoint = mapView.getProjection().fromPixels(touchX, touchY);
            return false;
        }
    }
    /**
     * MapView事件处理适配器，提供长按事件的实现
     */
    class MapViewEventAdapter implements MapView.MapViewEventListener {

        @Override
        public void moveStart(MapView paramMapView) {

        }

        @Override
        public void move(MapView paramMapView) {

        }

        @Override
        public void moveEnd(MapView paramMapView) {

        }

        @Override
        public void touch(MapView paramMapView) {

        }

        @Override
        public void longTouch(MapView paramMapView) {
            System.out.println("helloooolongtouchyou ");
            if (longTouchGeoPoint != null) {
                setLongTouchPoint2DOnMap(longTouchGeoPoint);
            }
        }

        @Override
        public void zoomStart(MapView paramMapView) {

        }

        @Override
        public void zoomEnd(MapView paramMapView) {

        }

        @Override
        public void mapLoaded(MapView paramMapView) {

        }
    }
    public Point2D getLocation() {
        Point2D point2D = new Point2D(location.getLongitude(), location.getLatitude());
        return point2D;
    }

    public void setLocationPoint2D(Point2D point2D) {
        locationPoint2D = point2D;
    }

    public Point2D getLocationPoint2D() {
        return locationPoint2D;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }



    private void geometryQuery(com.supermap.services.components.commontypes.Point2D point2D) {
        QueryByGeometryParameters p = new QueryByGeometryParameters();
        p.spatialQueryMode = SpatialQueryMode.INTERSECT;// 必设，空间查询模式，默认相交
        // 构建查询几何对象
        Geometry g = new Geometry();
        g.type = GeometryType.POINT;
//        g.points = new Point2D[]{new Point2D(339371.1679559936, 5013867.211060828)};
        g.points = new com.supermap.services.components.commontypes.Point2D[]{point2D};
        g.parts = new int[]{1};
        p.geometry = g;
        FilterParameter fp = new FilterParameter();
        fp.name = "用水地@lake#1";// 必设参数，图层名称格式：数据集名称@数据源别名
        p.filterParameters = new FilterParameter[]{fp};
        QueryByGeometryService qs = new QueryByGeometryService(DEFAULT_URL);
        qs.process(p, new MyQueryLandEventListener());
    }

    private class MyQueryLandEventListener extends QueryEventListener {
        @Override
        public void onQueryStatusChanged(Object o, EventStatus eventStatus) {
            if (o == null) return;
            QueryResult queryResult = (QueryResult) o;
            if (queryResult.quertyResultInfo.recordsets.length == 0)return;
            if(queryResult.quertyResultInfo.recordsets[0].getFeatures().length == 0)return;
            Feature f = queryResult.quertyResultInfo.recordsets[0].getFeature(0);
            String BSM =  f.fieldValues[4];
            String DLMC = f.fieldValues[9];
            String QSDWMC = f.fieldValues[12];
            String ZLDWMC = f.fieldValues[14];
            String TBMJ = f.fieldValues[19];
            String TBDLMJ = f.fieldValues[23];
            String XZDWMJ = f.fieldValues[20];
            String LXDWMJ = f.fieldValues[21];
            m_textfarmCode.setText(BSM);
            m_textfarmDLMC.setText(DLMC);
            m_textfarmQSDWMC.setText(QSDWMC);
            m_textfarmZLDWMC.setText(ZLDWMC);
            m_textfarmTBMJ.setText(TBMJ);
            m_textfarmTBDLMJ.setText(TBDLMJ);
            m_textfarmXZDWMJ.setText(XZDWMJ);
            m_textfarmLXDWMJ.setText(LXDWMJ);


        }
    }

//    // 距离量算结果
//    public void Measure_distance() {
//        // 构造查询参数
//        MeasureParameters parameters = new MeasureParameters();
//        com.supermap.services.components.commontypes.Point2D[] pts = { new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66) };
//        parameters.point2Ds =pts;
//        MeasureService service = new MeasureService(DEFAULT_URL);
//        MyMeasureEventListener listener = new MyMeasureEventListener();
//        service.process(parameters, listener,null);
//        try {
//            listener.waitUntilProcessed();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        // 结果验证
//        assertNotNull("The result is null!", result);
//        assertEquals("The distance of measure",6098355.576672727, result.distance);
//        assertEquals("The area of measure", -1.0, result.area);
//        assertEquals("The unit of measure", Unit.METER, result.unit);

//    }
//
//    // 量算监听器类
//    class MyMeasureEventListener extends MeasureService.MeasureEventListener {
//        @Override
//        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
//            // 量算结果
//            MeasureResult result = (MeasureResult) sourceObject;
//        }
//    }


//    // 面积量算结果
//    public void Measure_Area() {
//        // 构造查询参数
//        MeasureParameters parameters = new MeasureParameters();
//        com.supermap.services.components.commontypes.Point2D[] pts = { new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66), new com.supermap.services.components.commontypes.Point2D(73.88, 12.6),new com.supermap.services.components.commontypes.Point2D(23,34) };
//        parameters.point2Ds =pts;
//        MeasureService service = new MeasureService(DEFAULT_URL);
//        MyMeasureEventListener2 listener = new MyMeasureEventListener2();
//        service.process(parameters, listener, MeasureMode.AREA);
//        try {
//            listener.waitUntilProcessed();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        // 结果验证
//        assertNotNull("The result is null!", result);
//        assertEquals("The distance of measure",-1.0, result.distance);
//        assertEquals("The area of measure", 3.157590930368346E12, result.area);
//        assertEquals("The unit of measure", Unit.METER, result.unit);

//    }

//    // 量算监听器类
//    class MyMeasureEventListener2 extends MeasureService.MeasureEventListener {
//        @Override
//        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
//            // 量算结果
//            MeasureResult  result = (MeasureResult) sourceObject;
//        }
//    }
    // 经纬度坐标转换成投影坐标
//    public Double convertToProjection(double x,double y) {
//        CRSFactory crsFactory = new CRSFactory();
//        org.osgeo.proj4j.CoordinateReferenceSystem projUTN = crsFactory.createFromParameters("EPSG:32653", "+proj=utm +zone=53 +ellps=WGS84 +datum=WGS84 +units=m +no_defs");
//        Projection projection = projUTN.getProjection();
//        ProjCoordinate projCoordinate = new ProjCoordinate(x,y);
//        ProjCoordinate dst = new ProjCoordinate();
//        projection.project(projCoordinate, dst);
//        return new Double(dst);
//    }

    // 点击量算按钮弹出量算菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, 1, 0, "距离量算");
        menu.add(Menu.NONE, 2, 0, "面积量算");
        menu.add(Menu.NONE, 3, 0, "清除");
        return true;
    }
    /**
     * <p>
     * 展示距离量算
     * </p>
     */
    public void showDiatanceMeasure() {
        clean();
        drawStatic = 0;
        // 添加LineOverlay绘线，地图刷新
        if (!mapView.getOverlays().contains(touchOverlay)) {
            mapView.getOverlays().add(touchOverlay);
        }
        mapView.invalidate();
    }

    /**
     * <p>
     * 展示面积量算
     * </p>
     */
    public void showAreaMeasure() {
        clean();
        drawStatic = 1;
        // 添加PolygonOverlay绘面，地图刷新
        if (!mapView.getOverlays().contains(touchOverlay)) {
            mapView.getOverlays().add(touchOverlay);
        }
        mapView.invalidate();
    }

    // 清除
    public void clear() {
        if (mapView.getOverlays().contains(touchOverlay)) {
            mapView.getOverlays().remove(touchOverlay);
        }
        drawStatic = -1;
        clean();
        text.setVisibility(View.INVISIBLE);
        mapView.invalidate();
    }

    private void clean() {
        lineOverlay.setData(new ArrayList<Point2D>());
        polygonOverlay.setData(new ArrayList<Point2D>());
        geoPoints.clear();
        text.setText("");
    }

    // 绘面风格
    private Paint getPolygonPaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLUE);
        paint.setAlpha(50);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(2);
        return paint;
    }

    // 绘线风格
    private Paint getLinePaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLUE);
        paint.setAlpha(50);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);
        return paint;
    }

    /**
     * 触屏Overlay
     */
    class TouchOverlay extends Overlay {
        // 触屏的x坐标
        private int touchX;
        // 触屏的y坐标
        private int touchY;
        private List<Point> movePoints = new ArrayList<Point>();

        @Override
        public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
            if (event.getPointerCount() > 1) {// 发生多点触碰
                isMultiTouch = true;
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (movePoints.size() > 1) {// 如果发生平移，不绘制
                    double distance = 0;
                    for (int i = movePoints.size() - 1; i > 0; i--) {
                        double ds = Math.pow((movePoints.get(i).x - movePoints.get(i - 1).x), 2) + Math.pow((movePoints.get(i).y - movePoints.get(i - 1).y), 2);
                        if (ds > distance) {
                            distance = ds;
                        }
                    }
                    if (distance > 16) {
                        return false;
                    }
                }
                if (isMultiTouch) {// 如果发生多点触碰，不绘制
                    isMultiTouch = false;
                    return false;
                }
                text.setVisibility(View.VISIBLE);
                text.setTextSize(10);
                text.setText("");
                touchX = Math.round(event.getX());
                touchY = Math.round(event.getY());
                // 记录点击位置
                Point2D touchGeoPoint = mapView.getProjection().fromPixels(touchX, touchY);
                geoPoints.add(touchGeoPoint);
                if (drawStatic == 0) {
                    setOverlayData(lineOverlay);
                    if (geoPoints.size() >= 2) {
                        com.supermap.services.components.commontypes.Point2D[] pts = changePiont2D(geoPoints);
                        MeasureResult result = MeasureUtil.distanceMeasure(DEFAULT_URL, pts);
                        if (result != null) {
                            text.setText("量算结果：" + result.distance + "米");
                            Log.d("MeasureDemo", "量算结果" + text);
                        }
                    }

                } else if (drawStatic == 1) {
                    setOverlayData(polygonOverlay);
                    if (geoPoints.size() >= 3) {
                        com.supermap.services.components.commontypes.Point2D[] pts = changePiont2D(geoPoints);
                        MeasureResult result = MeasureUtil.areaMeasure(DEFAULT_URL, pts);
                        if (result != null) {
                            text.setText("量算结果：" + result.area + "平方千米");
                            Log.d("MeasureDemo", "量算结果" + text);
                        }
                    }
                }
            } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                movePoints.clear();
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                movePoints.add(new Point(Math.round(event.getX()), Math.round(event.getY())));
            }
            return false;
        }

        /**
         * 给Overlay设置点集合，开始绘制对象，并刷新地图
         *
         * @param overlay
         * @param gps
         */
        private void setOverlayData(Overlay overlay, List<Point2D> gps) {
            if (overlay == null) {
                return;
            }
            List<Point2D> geoPointList = new ArrayList<Point2D>();
            if (gps != null && gps.size() > 0) {
                copyList(gps, geoPointList);
            } else if (geoPoints.size() > 0) {
                copyList(geoPoints, geoPointList);
            }
            if (geoPointList.size() > 0) {
                if (overlay instanceof LineOverlay) {
                    ((LineOverlay) overlay).setData(geoPointList);

                } else if (overlay instanceof PolygonOverlay) {
                    ((PolygonOverlay) overlay).setData(geoPointList);
                }
                mapView.invalidate();
            }
        }

        private void copyList(List<Point2D> sourcegps, List<Point2D> targetgps) {
            for (int i = 0; i < sourcegps.size(); i++) {
                targetgps.add(new Point2D(sourcegps.get(i)));
            }
        }

        private void setOverlayData(Overlay overlay) {
            setOverlayData(overlay, null);
        }

        private com.supermap.services.components.commontypes.Point2D[] changePiont2D(List<Point2D> gps) {
            com.supermap.services.components.commontypes.Point2D[] pts = new com.supermap.services.components.commontypes.Point2D[gps.size()];
            for (int j = 0; j < gps.size(); j++) {
                pts[j] = new com.supermap.services.components.commontypes.Point2D(gps.get(j).x, gps.get(j).y);
            }
            return pts;
        }
    }
    @Override
    protected void onDestroy() {
        if (mapView != null) {
            mapView.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(listener!=null){
            locationManager.removeUpdates(listener);
            listener=null;
        }
        if(listener2!=null){
            locationManager.removeUpdates(listener2);
            listener2=null;
        }


    }
}
